package com.chwn.curiousdiary.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.api.IAccountApi;
import com.chwn.curiousdiary.api.IHomeApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.danikula.videocache.HttpProxyCacheServer;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Random;

import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

//import io.vov.vitamio.MediaPlayer;
//import io.vov.vitamio.Vitamio;
//import com.orhanobut.logger.Logger;


/**
 * Description:
 * 播放、暂停、上一曲、下一曲、播放模式、播放进度、通知栏
 * Copyright  : Copyright (c) 2017
 * Cany       : chwn
 * Author     : myshikin
 * Date       : 2017-03-29 09:58:32
 */
public class AudioService extends Service implements AudioManager.OnAudioFocusChangeListener {

    private static final String TAG             = "AudioService";
    public static final  String ACTION_PREPARED = "com.baidu.mobileplayer.AUDIOPREPARED";

    public static final int    PLAY_MODE_REPATE_ALL    = 0;
    public static final int    PLAY_MODE_REPATE_SINGLE = 1;
    public static final int    PLAY_MODE_RANDOM        = 2;
    public static final int    NOTIFY_CONTENT          = 3;
    public static final int    NOTIFY_PRE              = 4;
    public static final int    NOTIFY_NEXT             = 5;
    public static final int    NOTIFY_PLAY_SWITCH      = 10;
    public static final int    NOTIFY_CLOSE            = 12;
    public static final int    ONLY_OPEN               = 6;
    public static final int    FROM_MAIN               = 11;
    public static final int    HOME_ENTER              = 7;
    public static final int    NEWEST_ENTER            = 8;
    public static final int    HANDLER_PLAY            = 1;
    public static final String TOGGLEPAUSE_ACTION      = "com.chwn.curiousdiary.togglepause";
    public static final String NEXT_ACTION             = "com.chwn.curiousdiary.next_action";
    public static final String STOP_ACTION             = "com.chwn.curiousdiary.stop_action";
    public static final String PAUSE_ACTION            = "com.chwn.curiousdiary.pause_action";
    public static final String STOP_TIMMING_ACTION     = "com.chwn.curiousdiary.stop_timming_action";

    private String userToken;

    private int[] timmingTime = new int[]{0, 15 * 60 * 1000, 30 * 60 * 1000, 45 * 60 * 1000, 60 * 60 * 1000, 90 * 60 * 1000};

    /**
     * 播单Id
     */
    private String mPackageId = "id___";

    private int playMode = PLAY_MODE_REPATE_ALL;

    private MediaPlayer mediaPlayer;


    private boolean isCompleted;

    public ArrayList<StoryBean> getmAudioList() {
        return mAudioList;
    }

    private ArrayList<StoryBean> mAudioList;
    /**
     * 当前播放位置
     */
    private int mPosition = -1;

    /**
     * 上一首播放位置
     */
    private int prePlayPosition = -1;

    String mOriginUrl = "";
    String mUrl;

    private SharedPreferences sp;

    private AudioManager mAudioManager;

    private boolean isError;

    // 是否打开定时任务
    private boolean shouldPlayNext;
    // 结合定时任务使用
    private boolean shouldStopPlay;


    @Override
    public IBinder onBind(Intent intent) {
        return new Music();
    }

    public int getPlayMode() {
        return playMode;
    }

    public int getCurrentPlayPosition() {
        return mPosition;
    }

    public int getTimmingPosition() {
        return timmingPosition;
    }

    /**
     * 音乐的一个内部类
     */
    private class Music extends Binder implements IAudioService {

        @Override
        public AudioService getService() {
            return AudioService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sp = getSharedPreferences("play_mode", MODE_PRIVATE);
        playMode = sp.getInt("mode", PLAY_MODE_REPATE_ALL);

        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        IntentFilter filter = new IntentFilter();

        filter.addAction(PAUSE_ACTION);

        registerReceiver(mIntentReceiver, filter);

        //        Vitamio.isInitialized(getApplicationContext());

        Notifier.init(this);
        registerHeadsetPlugReceiver();
    }

    private void registerHeadsetPlugReceiver() {
        IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
        registerReceiver(headsetPlugReceiver, intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return super.onStartCommand(intent, flags, startId);
        }

        userToken = DiaryApplication.mInstance.getUserToken();

        int type = intent.getIntExtra(Constant.STORY_SERVICE_TYPE, -1);
        ArrayList<StoryBean> list;
        int position;
        switch (type) {
            case ONLY_OPEN:
                break;
            case FROM_MAIN:
                if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    //点击播放列表进入，如果音乐暂停，继续播放音乐
                    mediaPlayer.start();
                    mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
                    Notifier.showPlay(mAudioList.get(mPosition));
                }
                notifyUpdateUI();
                break;
            case NOTIFY_PLAY_SWITCH:  //暂停_播放
                switchPlayPause();
                notifyUpdateUI();
                break;
            case NOTIFY_CLOSE:  //停止播放&取消通知栏展示
                notifyUpdateUI();
                pause();
                break;
            case NOTIFY_CONTENT:  //通知栏
                notifyUpdateUI();
                break;
            case NOTIFY_PRE:  //上一曲
                playPre();
                break;
            case NOTIFY_NEXT:  //下一曲
                playNext();
                break;
            case -1:
            default:  //播放列表  数据添加 判断当前播放状态
                String packageId = intent.getStringExtra(Constant.PACKAGE_ID);
                list = (ArrayList<StoryBean>) intent.getSerializableExtra("list");
                position = intent.getIntExtra("position", -1);

                //是否从同一播单进入
                if (packageId.equals(mPackageId)) {
                    boolean isEqual = false;

                    try {
                        isEqual = (mAudioList.size() == list.size());
                    } catch (Exception e) {
                    }
                    if (isEqual) {
                        // 统计
                        storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);
                        mAudioList = list;
                        if (position == mPosition) {
                            //同一首歌
                            if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                                //点击播放列表进入，如果音乐暂停，继续播放音乐
                                mediaPlayer.start();
                            }
                            notifyUpdateUI();
                        } else if (position == -1) {
                            notifyUpdateUI();
                        } else {
                            mPosition = position;
                            playItem();
                            //                            Logger.e("进行数据统计 + 同一故事分类内切换播放位置");
                        }
                    } else {
                        // 统计
                        storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);
                        mAudioList = list;
                        if (mPosition == -1) {
                            if (position == -1) {
                                position = 0;
                            }
                            mPosition = position;
                            playItem();
                        } else if (mPosition == position) {
                            if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                                //点击播放列表进入，如果音乐暂停，继续播放音乐
                                mediaPlayer.start();
                            }
                            notifyUpdateUI();
                        } else {
                            if (position == -1) {
                                position = 0;
                            }
                            mPosition = position;
                            playItem();
                            //                            Logger.e("进行数据统计 + 同一故事分类内切换播放位置");
                        }
                    }
                } else {  //否
                    // 统计
                    storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);


                    mAudioList = list;
                    if (position == -1) {
                        mPosition = 0;
                        playItem();
                    } else {
                        mPosition = position;
                        playItem();
                        //                        Logger.e("进行数据统计 + 不同故事分类内切换播放位置");
                    }
                }
                mPackageId = packageId;

                break;
        }

        //        return START_REDELIVER_INTENT;
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * @param event
     */
    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.START_STORY_PLAY:
                if (mPosition != event.getPosition()) {
                    // TODO 未进行统计操作
                    //                    Logger.e("进行数据统计 + playQueue");
                    storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);
                    mPosition = event.getPosition();
                    playItem();

                } else {
                    switchPlayPause();
                    notifyUpdateUI();
                }
                break;
            case CustomEvent.GET_PLAY_STORY:
                if (mPosition == -1) {
                    EventBus.getDefault().post(new CustomEvent(CustomEvent.SEND_PLAY_STORY));
                } else {
                    CustomEvent customEvent = new CustomEvent(CustomEvent.SEND_PLAY_STORY);
                    customEvent.setMessage(mAudioList.get(mPosition));
                    EventBus.getDefault().post(customEvent);
                }
                break;

            case CustomEvent.TIMMING_START:
                timmingPosition = event.getPosition();
                if (timmingPosition != 0) {
                    timing(timmingTime[timmingPosition]);
                }
                break;
            case CustomEvent.TIMMING_STOP:
                timmingPosition = 0;
                shouldStopPlay = false;
                timmingStop();
                break;
        }
    }

    private Handler mPlayHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HANDLER_PLAY) {
                playStory((String) msg.obj);
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 上次切换音频时间
     */
    private long clickTime;

    private void playItem() {

        // 历史收听
        if (mPosition != -1) {
            listenHistory();
        }

        prePlayPosition = mPosition;
        if (mOriginUrl.equals(mAudioList.get(mPosition).getStoryUrl()) && !isError && !isCompleted) {
            notifyUpdateData();
            notifyUpdateUI();
            Notifier.showPlay(mAudioList.get(mPosition));
            mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
            return;
        }

        //避免二重唱
        if (mediaPlayer != null) {
            //            mediaPlayer.release();
            mediaPlayer.reset();
        }

        EventBus.getDefault().post(new CustomEvent(CustomEvent.STORY_PLAY_POSITION_CHANGE, mPosition));


        notifyUpdateData();

        Notifier.showPlay(mAudioList.get(mPosition));

        StoryBean audioBean = mAudioList.get(mPosition);
        final String url = audioBean.getData();
        mOriginUrl = url;

        playStory(url);
        //        // TODO 快速且频繁切换音频出现ANR
        //        if ((System.currentTimeMillis() - clickTime) > 300) {
        //        mPlayHandler.removeCallbacksAndMessages(null);
        //            mPlayHandler.post(new Runnable() {
        //                @Override
        //                public void run() {
        //                    Message obtain = Message.obtain();
        //                    obtain.what = HANDLER_PLAY ;
        //                    obtain.obj = url ;
        //                    mPlayHandler.sendMessage(obtain);
        //                }
        //            }) ;
        //
        //            clickTime = System.currentTimeMillis();
        //            Logger.e("300之外");
        //        } else {
        //            mPlayHandler.removeCallbacksAndMessages(null);
        //            mPlayHandler.postDelayed(new Runnable() {
        //                @Override
        //                public void run() {
        //                    Message obtain = Message.obtain();
        //                    obtain.what = HANDLER_PLAY ;
        //                    obtain.obj = url ;
        //                    mPlayHandler.sendMessage(obtain);
        //                    Logger.e("切换播放文件");
        //                }
        //            } , 300) ;
        //            clickTime = System.currentTimeMillis();
        //        }
        //
    }

    private void playStory(String url) {
        try {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
            }

            if (url.startsWith("http") && !url.contains("127.0.0.1")) {
                HttpProxyCacheServer proxy = CacheManager.getProxy(this, null);
                //此处转换了url，然后再赋值给mUrl
                url = proxy.getProxyUrl(url);
                boolean mCacheFile = (!url.startsWith("http"));
                //注册上缓冲监听
                if (!mCacheFile && CacheManager.instance() != null) {
                    proxy.registerCacheListener(CacheManager.instance(), mOriginUrl);
                }
            }
            mUrl = url;

            mediaPlayer.setDataSource(mUrl);
            mediaPlayer.setOnPreparedListener(new AudioPreparedListener());
            mediaPlayer.setOnCompletionListener(new AudioCompletionListener());
            mediaPlayer.setOnErrorListener(new AudioErrorListener());

            mediaPlayer.prepareAsync();


            mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void listenHistory() {
        String storyId = mAudioList.get(mPosition).getStoryId();
        if (!TextUtils.isEmpty(userToken)) {
            NetWork.getInstance()
                    .getApiService(IHomeApi.class)
                    .storyListenHistory(storyId, userToken, Constant.OSTYPE)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<HttpResult<Object>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(HttpResult<Object> objectHttpResult) {
                        }
                    });
        }
    }

    /**
     * 播放时间统计 播放时长未超过十秒的不予统计
     */
    private void storyPlayTimeStatist(long playTime, long totalTime) {
        //        long playTime = mediaPlayer.getCurrentPosition() / 1000L;

        // 容错
        if (isError || prePlayPosition == -1 || playTime < 10
                || TextUtils.isEmpty(userToken) || mAudioList == null
                || prePlayPosition > mAudioList.size() - 1 || playTime > totalTime) {

            return;
        }

        String storyId = mAudioList.get(prePlayPosition).getStoryId();

        //        Logger.e("storyName : " + mAudioList.get(prePlayPosition).getStoryTitle() + "  playTime : " + playTime + "  totalTime : " + totalTime);


        NetWork.getInstance()
                .getApiService(IAccountApi.class)
                .storyPlayTimeStatist(storyId, userToken, playTime, totalTime)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<Object>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(HttpResult<Object> objectHttpResult) {
                    }
                });
    }

    public StoryBean getCurrentPlayStory() {
        if (mPosition == -1 || mAudioList == null) {
            return null;
        }
        return mAudioList.get(mPosition);
    }


    /**
     * 音乐播放与暂停
     */
    public void switchPlayPause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            Notifier.showPause(mAudioList.get(mPosition));
            mAudioManager.abandonAudioFocus(this);
        } else if (mediaPlayer != null) {
            if (shouldPlayNext) {
                autoPlayNext();
                shouldPlayNext = false;
            } else {
                mediaPlayer.start();
                mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
                Notifier.showPlay(mAudioList.get(mPosition));
            }

        }
    }

    /**
     * 停止
     */
    public void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            mAudioManager.abandonAudioFocus(this);
        }
        if (mediaPlayer != null) {
            Notifier.showPause(mAudioList.get(mPosition));
            Notifier.cancelAll();
        }
    }

    /**
     * 获取音乐是否在播放
     */
    public boolean isPlaying() {
        if (mediaPlayer != null) {
            return mediaPlayer.isPlaying();
        }
        return false;
    }

    /**
     * 获取音乐的总时间   && mediaPlayer.isPlaying()
     */
    public int getMaxTime() {
        if (mediaPlayer != null) {
            return (int) mediaPlayer.getDuration();
        }
        return 0;
    }

    /**
     * 获取音乐当前播放的时间
     */
    public int getCurrentTime() {
        if (mediaPlayer != null) {
            return (int) mediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    /**
     * 设置音乐的播放进度
     */
    public void seekTo(int position) {
        if (mediaPlayer != null) {
            mediaPlayer.seekTo(position);
        }
    }

    /**
     * 播放上一曲
     */
    public void playPre() {
        if (playMode == PLAY_MODE_RANDOM) {
            autoPlayNext();
        } else {
            // 统计
            storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);
            //            Logger.e("进行数据统计 + playPre");
            if (mPosition != 0) {
                mPosition--;
                playItem();
            } else {
                if (mAudioList != null) {
                    mPosition = mAudioList.size() - 1;
                    playItem();
                }
            }

        }
    }

    //
    public void playNext() {
        if (playMode == PLAY_MODE_RANDOM) {
            autoPlayNext();
        } else {
            if (mPosition != mAudioList.size() - 1) {
                mPosition++;
            } else {
                mPosition = 0;
            }
            storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);
            playItem();
            // 统计
            //            Logger.e("进行数据统计 + playNext");
        }
    }

    /**
     * 切换标志位
     */
    public void switchPlayMode() {
        switch (playMode) {
            case PLAY_MODE_REPATE_ALL:
                playMode = PLAY_MODE_REPATE_SINGLE;
                break;
            case PLAY_MODE_REPATE_SINGLE:
                playMode = PLAY_MODE_RANDOM;
                break;
            case PLAY_MODE_RANDOM:
                playMode = PLAY_MODE_REPATE_ALL;
                break;
            default:
                break;
        }

        sp.edit().putInt("mode", playMode).apply();
    }

    /**
     * 根据播放模式自动播放下一首歌
     */
    private void autoPlayNext() {
        switch (playMode) {
            case PLAY_MODE_REPATE_ALL:
                if (mPosition == mAudioList.size() - 1) {
                    mPosition = 0;
                } else {
                    mPosition++;
                }
                break;
            case PLAY_MODE_REPATE_SINGLE:
                //单曲循环，不去改变posititon
                break;
            case PLAY_MODE_RANDOM:
                Random random = new Random();
                int r = random.nextInt(mAudioList.size());

                if (mAudioList.size() != 1) {
                    while (r == mPosition) {
                        r = random.nextInt(mAudioList.size());
                    }
                }

                mPosition = r;
                break;
            default:
                break;
        }
        // 统计
        storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);
        //        Logger.e("进行数据统计 + autoPlayNext");

        playItem();
    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_LOSS:
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    notifyUpdateUI();
                }
                Notifier.showPause(mAudioList.get(mPosition));
                break;
        }
    }

    AlarmManager  am;
    PendingIntent pendingIntent;

    public void timing(int time) {
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(PAUSE_ACTION),
                PendingIntent.FLAG_UPDATE_CURRENT);
        am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + time, pendingIntent);
    }

    public void timmingStop() {
        if (am != null && pendingIntent != null) {
            timmingPosition = 0;
            am.cancel(pendingIntent);
        }
    }

    private boolean isSend;

    /**
     * 音乐准备完成的监听
     */
    private class AudioPreparedListener implements MediaPlayer.OnPreparedListener {
        @Override
        public void onPrepared(MediaPlayer mp) {
            isCompleted = false;
            mediaPlayer.start();
            isError = false;
            notifyUpdateUI();
            if (!isSend) {
                EventBus.getDefault().post(new CustomEvent(CustomEvent.MAIN_NOTIFY));
                isSend = true;
            }
        }
    }

    /**
     * 通知音乐播放的界面更新UI
     */
    private void notifyUpdateUI() {
        Intent intent = new Intent(ACTION_PREPARED);
        notifyUpdateData();
        sendBroadcast(intent);
    }


    private void notifyUpdateData() {
        CustomEvent customEvent = new CustomEvent(CustomEvent.PLAY_STORY_DATA);
        StoryBean audioBean = mAudioList.get(mPosition);
        customEvent.setMessage(audioBean);
        customEvent.setTitle((mPosition + 1) + "/" + mAudioList.size());
        EventBus.getDefault().post(customEvent);
    }


    /**
     * 音乐播放完成的监听
     */
    private class AudioCompletionListener implements MediaPlayer.OnCompletionListener {
        @Override
        public void onCompletion(MediaPlayer mp) {
            isCompleted = true;
            if (!shouldStopPlay) {
                autoPlayNext();
                Logger.e("autoPlayNext");

            } else {
                shouldPlayNext = true;
                pause();
                timmingPosition = 0;
                notifyUpdateUI();
                shouldStopPlay = false;
                Logger.e("pause");
            }
        }
    }

    /**
     * 音乐播放出错
     */
    private class AudioErrorListener implements MediaPlayer.OnErrorListener {

        @Override
        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
            //            playItem();
            isError = true;
            EventBus.getDefault().post(new CustomEvent(CustomEvent.STORY_PLAY_ERROR));
            return true;
        }
    }

    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) {
                headsetPlug();
            }
        }
    };

    private void headsetPlug() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            mAudioManager.abandonAudioFocus(this);
        }
        if (mediaPlayer != null) {
            Notifier.showPause(mAudioList.get(mPosition));
        }
        notifyUpdateUI();
    }

    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(final Context context, final Intent intent) {
            handleCommandIntent(intent);
        }
    };


    private int timmingPosition;

    private void handleCommandIntent(Intent intent) {
        if (PAUSE_ACTION.equals(intent.getAction())) {
            shouldStopPlay = true;
            /*pause();
            timmingPosition = 0;
            notifyUpdateUI();*/
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        // 统计
        if (prePlayPosition != -1) {
            storyPlayTimeStatist(getCurrentTime() / 1000, getMaxTime() / 1000);
        }

        Notifier.onDestory();
    }
}
